//
//  VCShowTicket.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/1/22.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit

class VCShowTicket: VCBase {
    
    // 日期选择
    private lazy var dateSelectView: DateSelectView = {
        let view = DateSelectView(frame: CGRect(x: 0, y: realHeight, width: SCREEN_WIDTH, height: ROW_HEIGHT + MARGIN40))
        return view
    }()
    
    // 查票显示
    private lazy var showTicketBodyView: ShowTicketBodyView = {
        let ticket = ShowTicketBodyView()
        let ticketY = dateSelectView.frame.maxY
        ticket.frame = CGRect(x: 0, y: ticketY, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - ticketY)
        return ticket
    }()
    
    // 请求数据
    public var requestDict: NSDictionary?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        init_veiws()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        init_datas()
        init_event()
    }
}

extension VCShowTicket {
    
    func searchFilghts(date:String,isCallback:Bool = true) -> Void {
        // 拼接数据
        let items = NSMutableDictionary()
        items.setValue(date, forKey: "departdate")
        items.setValue(requestDict!.value(forKey: "city"), forKey: "city")
        items.setValue(requestDict!.value(forKey: "endcity"), forKey: "endcity")
        if let cabinname = requestDict?.value(forKey: "cabinname"),!(cabinname as! String).elementsEqual("舱位不限") {
            items.setValue(cabinname, forKey: "cabinname")
        }
        if let flightnumberid = requestDict?.value(forKey: "flightnumberid") {
            items.setValue(flightnumberid, forKey: "flightnumberid")
        }
        // 请求
        self.doPost(api: "search/flightplay", dict: items) { (dict) in
            if self.isServerSuccess(dict: dict) != 1200 {
                self.dateSelectView.ticketNumber = 0
                self.showTicketBodyView.removeFromSuperview()
                self.noDataView.resetTipText = "未搜到相应航班,请重新选择"
                self.view.addSubview(self.noDataView)
                return
            }
            self.view.addSubview( self.showTicketBodyView)
            // 解析数据
            let bodyRequest = dict.value(forKey: SP_BODYREQUEST) as! NSDictionary
            // 航班线数据
            let flights = bodyRequest.value(forKey: "flights") as! NSArray
            var flightArrs = [FlightInfo]()
            for item in flights {
                let flight = FlightInfo(dict: item as! [String : Any])
                flightArrs.append(flight)
            }
            // 航班计划数据
            let flightplays = bodyRequest.value(forKey: "flightplays") as! NSArray
            var flightplayArrs = [FlightPlayInfo]()
            for item in flightplays {
                let flightplay = FlightPlayInfo(dict: item as! [String : Any])
                flightplayArrs.append(flightplay)
            }
            // 机票价格数据
            let prices = bodyRequest.value(forKey: "prices") as! NSArray
            self.dateSelectView.firstmoneys = prices as? [Int]
            // 查出来的机票
            let info = FlightStruct(flight: flightArrs, flightPlay: flightplayArrs)
            let temp = self.getSearchTicketInfo(info: info)
            self.dateSelectView.ticketNumber = temp.count
            // 更新显示的机票信息
            self.showTicketBodyView.tickets = temp
            // 选中日期
            if !isCallback {
                let day = AirLineUtil.shareInstance.str2Date(str: date)
                if day < 12, day >= 0 {
                    self.dateSelectView.selectDate(index: day)
                }
            }
        }
    }
    
    private func init_event() -> Void {
        dateSelectView.complete = { date in
            self.searchFilghts(date: date)
        }
        
        // 用户下单
        showTicketBodyView.complete = {item in
            if let ticket = self.showTicketBodyView.tickets?[item] {
                let vc = VCBuyTicket()
                vc.ticketInfo = ticket
                self.pushNextVcHideBottomBar(vc: vc)
            }
        }
    }
    
    // 查出来的机票
    func getSearchTicketInfo(info:FlightStruct) -> [TicketInfo] {
        var temp = [TicketInfo]()
        for i in 0..<info.flights.count {
            // 航班线
            let flight = info.flights[i]
            // 航班计划
            let flightPlay = info.flightPlays[i]
            let tic = TicketInfo()
            tic.craft = flight.craft
            tic.city = flightPlay.city
            tic.miletime = flight.miletime
            tic.endcity = flightPlay.endcity
            tic.cabinname = flight.cabinname
            // 是否是往返请求
            if let arrivaldate = self.requestDict!.value(forKey: "arrivaldate"){
                tic.arrival_date = arrivaldate as? String
            }
            // 是否是变更订单
            if let changeOrder = self.requestDict!.value(forKey: "orderid"){
                tic.orderid = changeOrder as? String
                tic.orderprice = self.requestDict!.value(forKey: "orderprice") as! Int
                // 文字修改
                self.showTicketBodyView.submitText = "变更"
            }
            tic.flight_name = flight.flightname
            tic.depart_date = flightPlay.departdate
            tic.depart_time = flightPlay.departtime
            tic.arrival_time = flightPlay.arrivaltime
            tic.depart_terminal = flight.departterminal
            tic.food = flight.food == 0 ? "有餐" : "无餐"
            tic.arrival_terminal = flight.arrivalterminal
            tic.flight_number = flight.flightnumberid
            tic.luggage = String(describing: flight.luggage)
            tic.mileage = String(describing: flight.mileage)
            tic.ticket_price = String(describing: flight.ticketprice)
            tic.ticket_count = String(describing: flight.ticketcount)
            temp.append(tic)
        }
        // 返回
        return temp
    }
    
    private func init_datas() -> Void {
        guard let dict = requestDict else {
            return
        }
        guard let departdate = dict.value(forKey: "departdate") as? String else {
            return
        }
        // 显示数据
        searchFilghts(date: departdate,isCallback: false)
    }
    
    private func init_veiws() -> Void {
        view.addSubview(backroundWhite)
        view.addSubview(dateSelectView)
        view.addSubview(showTicketBodyView)
    }
}
